package net.dgg.dggcloud.service.jrcrm.aspect;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.dgg.dggcloud.core.idwork.KeyWorker;
import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.entity.Role;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.constant.SysRecordConstant;
import net.dgg.dggcloud.service.jrcrm.constant.OpreateEnum;
import net.dgg.dggcloud.service.jrcrm.constant.OpreateTypeEnum;
import net.dgg.dggcloud.service.jrcrm.service.log.SysModifyAuthRecordService;
import net.dgg.dggcloud.service.jrcrm.utils.IpUtil;
import net.dgg.dggcloud.service.service.RoleService;
import net.dgg.dggcloud.service.service.user.UserService;
import net.dgg.framework.tac.mq.rabbitmq.queue.DggMessageSendUtil;

@Aspect
@Component
public class UserAuthSaveAspect {
	private Logger logger = Logger.getLogger(UserAuthSaveAspect.class);

	@Autowired
	protected KeyWorker keyWorker;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	@Pointcut("execution(public * net.dgg.dggcloud.platform.action.UserController.authSave(..))")
	public void webLog() {
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Before("webLog()")
	public void before(JoinPoint jp) {
		try {
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = attributes.getRequest();
			User user = SessionManager.getCurrentUser();
			Object[] objs = jp.getArgs();
			Long userId = Long.valueOf(objs[2].toString());
			User vuser = userService.getUserById(userId);

			Map record = new HashMap<>();
			record.put("ip", IpUtil.getIPAddress(request));
			record.put("opreate", OpreateEnum.USERROLE.getOpreate());
			record.put("opreateTime", DateUtil.dateToString(new Date()));
			record.put("userLoginname", user.getLoginName());
			record.put("userName", user.getName());
			record.put("vuserLoginname", vuser.getLoginName());
			record.put("vuserName", vuser.getName());
			record.put("clazz", SysModifyAuthRecordService.class);

			List<Long> olds = new ArrayList<>();

			Iterator<Map> imap = userService.findRoleIdsByUserId(userId).iterator();
			while (imap.hasNext()) {
				Map map = imap.next();
				olds.add(Long.valueOf(map.get("roleid").toString()));
			}
			Long[] longs = objs[1] == null ? new Long[0] : (Long[]) objs[1];
			List<Long> news = new ArrayList<>(Arrays.asList(longs));
			List<Long> temps = new ArrayList<>();
			temps.addAll(olds);
			olds.removeAll(news);
			news.removeAll(temps);

			if (!olds.isEmpty()) {// 删除
				String strolds = StringUtils.join(olds, ",");
				List<Role> roles = roleService.findCodeAndName4Ids(strolds);
				record.put("id", keyWorker.nextId());
				record.put("opreateType", OpreateTypeEnum.DELETE.getType());
				StringBuffer sb = new StringBuffer();
				sb.append("{");
				Iterator<Role> irole = roles.iterator();
				while (irole.hasNext()) {
					Role role = irole.next();
					sb.append(role.getRoleKey() + ":" + role.getName() + ",");
				}
				sb.deleteCharAt(sb.length() - 1);
				sb.append("}");
				record.put("modifyContent", sb.toString());
				logger.info("======================>发送消息...");
				DggMessageSendUtil.putMessage(SysRecordConstant.QUEUENAME, record);
			}
			if (!news.isEmpty()) {// 添加
				String strnews = StringUtils.join(news, ",");
				List<Role> roles = roleService.findCodeAndName4Ids(strnews);
				record.put("id", keyWorker.nextId());
				record.put("opreateType", OpreateTypeEnum.ADD.getType());
				StringBuffer sb = new StringBuffer();
				sb.append("{");
				Iterator<Role> irole = roles.iterator();
				while (irole.hasNext()) {
					Role role = irole.next();
					sb.append(role.getRoleKey() + ":" + role.getName() + ",");
				}
				sb.deleteCharAt(sb.length() - 1);
				sb.append("}");
				record.put("modifyContent", sb.toString());
				logger.info("======================>发送消息...");
				DggMessageSendUtil.putMessage(SysRecordConstant.QUEUENAME, record);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
